<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\ResponseException;
use App\Http\Requests\Admin\UserAddRequest;
use App\Http\Requests\Admin\UserUpdateRequest;
use App\Models\Admin;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 会员列表
     * User: ihome
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request,User $user)
    {
        $where = [];

        if($username = $request->input('username')){
            $where[] = ['username','like',"%$username%"];
        }

        if($nickname = $request->input('nickname')){
            $where[] = ['nickname','like',"%$nickname%"];
        }

        if($company_name = $request->input('company_name')){
            $where[] = ['company_name','like',"%$company_name%"];
        }

        if($admin_id = $request->input('admin_id')){
            $where['created_admin_id'] = $admin_id;
        }

        $status = $request->input('status');
        if($status == '0'){
            $where['status'] = '0';
        }else if($status){
            $where['status'] = $status;
        }

        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');

        if($start_time && $end_time){
            $where[] = [
                'created_at','>=',$start_time,

            ];
            $where[] = [
                'created_at','<',$end_time
            ];
        }else if($start_time){
            $where[] = ['created_at','>=',$start_time];
        }else if($end_time){
            $where[] = ['created_at','<',$end_time];
        }

        $id = auth('admin')->id();

        if($id != 1){ //非超管 只能看到自己的
            $where['created_admin_id'] = $id;
        }

        $userList = User::query()
            ->with(['user_info'=>function($query){
                return $query->select('user_id','sex','age');
            }])
            ->where($where)
            ->orderBy('id','desc')
            ->paginate(10);

        $count = User::query()
            ->with(['admin'=>function($query){
                return $query->select('id','nickname as admin_name')->withTrashed();
            }])
            ->where($where)
            ->orderBy('id','desc')
            ->count();

        $admin_list = Admin::query()->select('id','nickname')->get();

        return view('admin.user.index',compact('userList','admin_list','count'));
    }

    public function create()
    {
        return view('admin.user.create');
    }

    public function store(UserAddRequest $request,User $user)
    {
        $data = $request->except('_token');

        $insertData = [
            'username'=>$data['username'],
            'nickname'=>$data['nickname'],
            'password'=>bcrypt($data['password']),
            'show_pswd'=>$data['password'],
            'company_name'=>$data['company_name'],
            'created_admin_id'=>auth('admin')->id(),
            'status'=>$data['status'],
            'start_time'=>$data['start_time'],
            'end_time'=>$data['end_time'],
        ];

        $user->fill($insertData);
        $user->save();

        return redirect()->route('admin.user.index')->with('success','添加成功');
    }

    public function edit($id,Request $request)
    {
        $auth_id = auth('admin')->id();

        $where = [];

        if($auth_id != 1){
            $where['created_admin_id'] = $auth_id;
        }

        $user = User::query()->where($where)->findOrFail($id);

        return view('admin.user.edit',compact('user'));
    }

    public function update($id,UserUpdateRequest $request)
    {
//        $id = $request->input('id');
        $user = User::findOrFail($id);

        $auth_id = auth('admin')->id();
        if($auth_id != 1 && $auth_id != $user->created_admin_id){
            return redirect()->back()->with('danger','不能修改非当前管理员的会员');
        }

        $data = $request->except('_token');

        $updateData = [
            'username'=>$data['username'],
            'nickname'=>$data['nickname'],
            'company_name'=>$data['company_name'],
            'status'=>$data['status'],
            'start_time'=>$data['start_time'],
            'end_time'=>$data['end_time'],
        ];

        if($data['password']){
            $updateData['show_pswd']=$data['password'];
            $updateData['password'] = bcrypt($data['password']);
        }

        $user->fill($updateData);
        $user->where('id',$id)->update($updateData);

        return redirect()->route('admin.user.index')->with('success','修改成功');
    }

    public function showUser(Request $request,$id)
    {
        //显示用户信息
        $user = User::findOrFail($id);
        return view('admin.user.show',compact('user'));
    }

    public function destroy($id,Request $request)
    {
        $auth_id = auth('admin')->id();

        $user = User::findOrFail($id);

        if($auth_id != 1 && $user->created_admin_id != $auth_id){
            return redirect()->back()->with('danger','不能删除非自己的会员');
        }

        $user->delete();

        return redirect()->route('admin.user.index')->with('success','删除成功');
    }

    /**
     * ajax改变用户状态
     * User: ihome
     */
    public function ajaxChangeUserStatus()
    {
        if(\request()->method() == 'POST'){
            $user_id = (int) \request()->input('user_id');
            $user = User::find($user_id);

            if($user){
                if($user->status == 1){
                    $user->status = 0;
                }else{
                    $user->status = 1;
                }

                $user->save();

                throw new ResponseException(200,'修改成功',['status'=>$user->status]);
            }else{
                throw new ResponseException(404,'用户不存在');
            }
        }
    }
}
